cmake_minimum_required(VERSION 3.10)
file(STRINGS "VERSION" VERSION_CONTENTS)

if(CMAKE_EXTRA_SYSTEM MATCHES QNX)
    foreach(LINE ${VERSION_CONTENTS})
        string(REGEX REPLACE " |\t" "" LINE ${LINE})
        string(REGEX MATCH "(^[^=]+)_qnx" VERSION_NAME ${LINE})
        if(NOT VERSION_NAME)
            continue()
        endif()
        string(REPLACE "${VERSION_NAME}=" "" VERSION_VALUE ${LINE})
        string(REPLACE "_qnx" "_version" VERSION_NAME ${VERSION_NAME})
        set_property(GLOBAL PROPERTY ${VERSION_NAME} "${VERSION_VALUE}")
        message(STATUS "${VERSION_NAME}=${VERSION_VALUE}")
        
        string(REGEX MATCH "(^[0-9]+)" VERSION_MAJOR ${VERSION_VALUE})
        set_property(GLOBAL PROPERTY ${VERSION_NAME}_major "${VERSION_MAJOR}")
        message(STATUS "${VERSION_NAME}_major=${VERSION_MAJOR}")
    endforeach()
elseif(CMAKE_EXTRA_SYSTEM MATCHES X86_64)
    foreach(LINE ${VERSION_CONTENTS})
        string(REGEX REPLACE " |\t" "" LINE ${LINE})
        string(REGEX MATCH "(^[^=]+)_x86_64" VERSION_NAME ${LINE})
        if(NOT VERSION_NAME)
            continue()
        endif()
        string(REPLACE "${VERSION_NAME}=" "" VERSION_VALUE ${LINE})
        string(REPLACE "_x86_64" "_version" VERSION_NAME ${VERSION_NAME})
        set_property(GLOBAL PROPERTY ${VERSION_NAME} "${VERSION_VALUE}")
        message(STATUS "${VERSION_NAME}=${VERSION_VALUE}")

        string(REGEX MATCH "(^[0-9]+)" VERSION_MAJOR ${VERSION_VALUE})
        set_property(GLOBAL PROPERTY ${VERSION_NAME}_major "${VERSION_MAJOR}")
        message(STATUS "${VERSION_NAME}_major=${VERSION_MAJOR}")
    endforeach()
else()
    foreach(LINE ${VERSION_CONTENTS})
        string(REGEX REPLACE " |\t" "" LINE ${LINE})
        string(REGEX MATCH "(^[^=]+)_linux" VERSION_NAME ${LINE})
        if(NOT VERSION_NAME)
            continue()
        endif()
        string(REPLACE "${VERSION_NAME}=" "" VERSION_VALUE ${LINE})
        string(REPLACE "_linux" "_version" VERSION_NAME ${VERSION_NAME})
        set_property(GLOBAL PROPERTY ${VERSION_NAME} "${VERSION_VALUE}")
        message(STATUS "${VERSION_NAME}=${VERSION_VALUE}")

        string(REGEX MATCH "(^[0-9]+)" VERSION_MAJOR ${VERSION_VALUE})
        set_property(GLOBAL PROPERTY ${VERSION_NAME}_major "${VERSION_MAJOR}")
        message(STATUS "${VERSION_NAME}_major=${VERSION_MAJOR}")

    endforeach()
endif()

execute_process(
	COMMAND	git log -1 --format=%H_%at
	WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
	OUTPUT_VARIABLE GIT_VERSION
	ERROR_VARIABLE GIT_ERROR
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

if("${GIT_ERROR}" STREQUAL "")
    message(STATUS "GIT_VERSION=${GIT_VERSION}")
else()
    message(STATUS "GIT_ERROR=${GIT_ERROR}")
    string(TIMESTAMP GIT_VERSION "%Y%m%d%H%M%S")
    message(STATUS "GIT_VERSION=${GIT_VERSION}")
endif()

add_definitions( -DGIT_VERSION=\"Commit:${GIT_VERSION}\")
